package cn.base.web.support.config;

import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.DurationSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Configuration
@EnableScheduling
public class DefaultConfiguration {
	

	@Bean
	public RestTemplate restTemplate() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setConnectTimeout(1000*3);
		factory.setReadTimeout(1000*3);
		RestTemplate restTemplate= new RestTemplate(factory);
		//也可以支持text/html
		//MappingJackson2HttpMessageConverter messageConverter=new MappingJackson2HttpMessageConverter();
		//messageConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_HTML));
		//restTemplate.getMessageConverters().add(messageConverter);
		return restTemplate;
	}

	/**
	 * 前端展现用，不需要反序列化
	 * 如何自定义ObjectMapper
	 * https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-jackson-objectmapper
	 * 数字全部转string可以使用spring.jackson.generator.write-numbers-as-strings=true
	 * bigdecimal只是toPlain不转string可以使用spring.jackson.generator.write-bigdecimal-as-plain=true
	 * @return
	 */
	@Bean
	public Jackson2ObjectMapperBuilderCustomizer defaultObjectMapperCustomizer() {
        return jacksonObjectMapperBuilder -> {
            //
            jacksonObjectMapperBuilder
                    .serializerByType(Long.class, ToStringSerializer.instance)
                    .serializerByType(BigDecimal.class, NumberSerializer.bigDecimalAsStringSerializer())
                    .serializerByType(Long.TYPE, ToStringSerializer.instance)//基本类型,不设置 基本long类型不能转string
                    .serializerByType(BigInteger.class, ToStringSerializer.instance)//mysql 无符号映射为BigInteger，有符号映射为Long
                    //解决LocalDateTime返回时间带T
                    .serializerByType(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .serializerByType(Duration.class, DurationSerializer.INSTANCE)


            //.deserializerByType()
            ;
        };
	}
}
